# -*- coding = utf-8 -*-
# @Time: 2024/06/29
# @Author: Bobby
# @File: 购物系统.py
# @Software: PyCharm

# -*- version1.0 -*-

# import time
#
# goods = [['电脑', 5000], ['电视', 1000], ['苹果', 5], ['梨', 5], ['鸡蛋', 1], ['西红柿', 0.5],
#          ['空调', 2000], ['冰箱', 2000], ['面条', 1], ['本', 3], ['铅笔', 1], ['钢笔', 10],
#          ['橡皮', 0.5], ['美工刀', 5], ['尺子', 10]]  # 创建一个商品列表，用于存放商品
#
# # 初始化全局变量
# user_money = 5000  # 用户初始余额
# cart = []  # 购物车，使用列表存储商品（商品名称和价格的元组）
# cart_total_price = 0  # 购物车中商品的总价
#
#
# # 根据商品名称查找价格
# def find_product_price(product_name):
#     for product in goods:
#         if product[0] == product_name:
#             return product[1]
#     return None  # 如果商品不存在，返回None
#
#
# # 将商品添加到购物车
# def add_to_cart(product_name):
#     global cart, cart_total_price
#     price = find_product_price(product_name)
#     if price is not None and check_affordability(price):
#         cart.append((product_name, price))
#         cart_total_price += price
#         print(f"恭喜，购买成功！您的卡余额还剩{user_money - cart_total_price}元")
#     elif price is None:
#         print("没有这个商品，别瞎弄！")
#     else:
#         print("穷鬼，钱不够！请到其他超市购买！")
#
#
# # 检查是否有足够的金额购买商品
# def check_affordability(price):
#     global user_money
#     return user_money - cart_total_price >= price
#
#
# # 打印购物小票
# def print_receipt():
#     global cart, cart_total_price
#     if cart:
#         print('正在打印购物小票请耐心等待...')
#         time.sleep(1)
#         print("购物小条：")
#         print("商品\t\t价格")
#         for product, price in cart:
#             print(f"{product}\t\t{price}元")
#         print(f"总价：\t{cart_total_price}元")
#     else:
#         print("购物车为空！")
#
#
# print("欢迎来到购物商场！")
# while True:
#     choice = input("请输入您想购买的商品名称（或输入Q/q退出）：")
#     if choice.upper() == 'Q':
#         break
#
#     add_to_cart(choice)
#
# print_receipt()

# -*- version2.0 -*-

import time
import random

# 创建商品目录，格式为[商品名称，价格]
goods = [['电脑', 5000], ['电视', 1000], ['苹果', 5], ['梨', 5], ['鸡蛋', 1], ['西红柿', 0.5],
         ['空调', 2000], ['冰箱', 2000], ['面条', 1], ['本', 3], ['铅笔', 1], ['钢笔', 10],
         ['橡皮', 0.5], ['美工刀', 5], ['尺子', 10]]

# 创建优惠券列表，格式为 [商品名称, 折扣]
coupons = [['空调', 0.8], ['电视', 0.9], ['冰箱', 0.95], ['电脑', 0.85], ['鸡蛋', 0.5],
           ['美工刀', 0.98], ['面条', 0.95], ['钢笔', 0.7], ['梨', 0.85], ['尺子', 0.9]]

# 初始化全局变量
user_money = 5000  # 用户初始余额
cart = []  # 购物车，使用列表存储商品（商品名称和价格的元组）
cart_total_price = 0  # 购物车中商品的总价
used_coupon = None  # 已使用的优惠券


# 定义根据商品名称查找价格
def find_product_price(product_name):
    for product in goods:  # 循环遍历商品列表，从商品列表中查找商品价格
        if product[0] == product_name:
            return product[1]
    return None


# 将商品添加到购物车
def add_to_cart(product_name):
    global cart, cart_total_price, used_coupon
    price = find_product_price(product_name)  # 匹配商品价格
    if price is not None:
        if product_name == used_coupon[0]:
            discount = used_coupon[1]
            print(f"您已经使用了{used_coupon[0]}的优惠券，折扣为{discount:.0%}。")
            discounted_price = price * discount
        else:
            discounted_price = price
        if check_affordability(discounted_price):
            # 检查购物车中是否已经存在该商品
            for item in cart:
                if item[0] == product_name:
                    item[2] += 1  # 数量+1
                    break
            else:
                cart.append([product_name, discounted_price, 1])  # 添加商品到购物车
            cart_total_price += discounted_price
            print(f"恭喜，购买成功！您的卡余额还剩{user_money - cart_total_price}元")
        else:
            print("穷鬼，钱不够！请到其他超市购买！")
    else:
        print("没有这个商品，别瞎弄！")


# 检查用户是否有足够的余额购买商品
def check_affordability(price):
    global user_money
    return user_money - cart_total_price >= price


# 从购物车中移除商品
def remove_from_cart(product_name):
    global cart, cart_total_price
    for item in cart[:]:
        if item[0] == product_name:
            cart.remove(item)
            cart_total_price -= item[1]
            print(f"{product_name}已从购物车中移除，您的卡余额为{user_money - cart_total_price}元")
            break
    else:
        print(f"{product_name}不在购物车中！")


# 打印购物小条
def print_receipt():
    global cart, cart_total_price, user_money
    if cart:
        print('正在打印购物小票请耐心等待...')
        time.sleep(2)
        print("购物小条：")
        print('                    豪华购物超市                 ')
        print('-----------------------------------------------')
        print("商品\t\t\t\t价格\t\t\t\t数量\t\t\t小计")
        max_len = max(len(item[0]) for item in cart)
        for item in cart:
            product_name = item[0]
            price = item[1]
            quantity = item[2]
            total_price = price * quantity
            # 根据长度调整\t数量来对齐
            print(f"{product_name.ljust(max_len + 2, ' ')}\t{str(price).rjust(10, ' ')}元\t\t\t{str(quantity).rjust(3, ' ')}\t\t{str(total_price).rjust(5, ' ')}元")

        print(f"{'总价：'.ljust(15, ' ')}{str(cart_total_price).rjust(28, ' ')}元")
        print(f"{'卡余额：'.ljust(15, ' ')}{str(user_money - cart_total_price).rjust(28, ' ')}元")

        total_items = sum(item[2] for item in cart)
        print(f"{'购物数量：'.ljust(11, ' ')}{str(total_items).rjust(28, ' ')}个商品")
        print('-----------------------------------------------')
        print(f"购物时间：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}")
        print('豪华购物超市祝您生活愉快！欢迎您的下次光临~')
    else:
        print("购物车为空！")


# 随机抽取一张优惠券
def draw_coupon():
    global used_coupon
    if coupons:
        used_coupon = random.choice(coupons)
        print(f"恭喜您抽中了{used_coupon[0]}的{used_coupon[1]:.0%}优惠券！")
    else:
        print("没有优惠券可以抽取了！")


print("欢迎来到购物商场！")
draw_coupon()  # 用户进商场之前抽取优惠券

while True:
    choice = input("请输入您想购买的商品名称（或输入R/r退货，Q/q退出）：")
    if choice.upper() == 'Q':
        break
    elif choice.upper() == 'R':
        product_to_remove = input("请输入要退货的商品名称：")
        remove_from_cart(product_to_remove)
    else:
        add_to_cart(choice)
print_receipt()
